package com.saunter.utils;

import com.saunter.service.user.AdminService;
import com.saunter.utils.exception.ExceptionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminService adminService;
    //before request(before controller)
    @Resource
    private ExceptionManager exceptionManager;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String request_url = request.getRequestURI();

        Matcher matcher = Pattern.compile("^/(admin|user)/(\\w+)(/\\w+)*$").matcher(request_url);
        if(matcher.find()  && !"login".equals(matcher.group(2))) {
            String operator_type = matcher.group(1);
            String system_append_admin_id = request.getParameter("admin".equals(operator_type) ? "system_append_admin_id" : "system_append_id_num");
            if(null == system_append_admin_id || "".equals(system_append_admin_id)) {
                throw exceptionManager.create("Lg000");
            }
        }
        return true;
    }
    //after request deal,before view draw(after controller)
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //after view draw
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
